package com.jiang.jetpackdemo.utils


import android.content.Context
import com.bumptech.glide.Glide
import kotlinx.coroutines.*
import java.io.File

/**
 *
 * @ProjectName:    JetpackDemo
 * @ClassName:      ImageCacheUtil
 * @Description:     java类作用描述
 * @Author:         江
 * @CreateDate:     2020/4/4 17:08
 */
class CacheUtil(private val context: Context) {
    companion object {
        private const val DEFAULT_DISK_CACHE_DIR = "/image_manager_disk_cache"
    }

    private fun formatSize(size: Long, useMB: Boolean): String {
        val kb = size.shr(10)
        return if (useMB) String.format("%.2f", kb.toDouble() / 1024) else kb.toString()
    }

    fun getImageCacheSize(): String {
        val size = getAllFileSize(File(context.cacheDir.path + DEFAULT_DISK_CACHE_DIR))
        return formatSize(size, true)
    }

    private fun getAllFileSize(file: File): Long {
        var size = 0L
        val listFiles = file.listFiles()
        if (listFiles.isNullOrEmpty()) return size

        //遍历目录
        for (f in listFiles) {
            size += if (f.isDirectory) {
                // 如果是目录，递归
                getAllFileSize(f)
            } else {
                //是文件，获取长度累加
                f.length()
            }
        }
        return size
    }

   suspend fun clearImageCacheSize() {
       withContext(Dispatchers.IO) {
            Glide.get(context).clearDiskCache()
        }
    }

    suspend fun getVideoRequestCacheSize(): String {
        val cache = SPUtil(context).getVideoRequestCacheSuspend()
        return formatSize(cache.toByteArray().size.toLong(), false)
    }

    fun clearVideoRequestCache() {
        SPUtil(context).setVideoRequestCache("")
    }

}